import { isArray } from '/@/utils/is';
import { FormSchema } from '/@/components/Table';
import { buildUUID } from '/@/utils/uuid';
export interface NodeList {
  jobName: string;
  title: string;
  label: string;
  value: string;
}

export interface FormDataOptions {
  code?: string;
  name?: string;
  label?: string;
  value?: string;
  options?: any;
  title?: string;
  kind?: string;
  math?: string;
}

export const formSchema: FormSchema[] = [
  {
    field: 'divider-basic',
    component: 'Divider',
    label: '回写设置',
    colProps: {
      span: 24,
    },
  },
  {
    field: 'dbSource',
    label: '数据源',
    component: 'Select',
    colProps: {
      span: 24,
    },
    componentProps: {
      optionFilterProp: 'label',
      showSearch: true,
      options: [],
      getPopupContainer: () => document.body,
    },
    ifShow: false,
  },
  {
    field: 'scene',
    label: '回写时机',
    colProps: {
      span: 24,
    },
    component: 'RadioGroup',
    defaultValue: 'nodeFinish',
    componentProps: {
      options: [
        {
          label: '添加',
          value: 'add',
        },
        {
          label: '修改',
          value: 'edit',
        },
        {
          label: '删除',
          value: 'del',
        },
      ],
    },
  },
  {
    label: '回写方式',
    field: 'writeBackType',
    component: 'Select',
    colProps: {
      span: 24,
    },
    defaultValue: '0',
    componentProps: {
      optionFilterProp: 'label',
      options: [
        {
          label: '仅更新数据',
          value: '0',
        },
        {
          label: '仅插入数据',
          value: '1',
        },
        {
          label: '更新并插入数据',
          value: '2',
        },
      ],
      getPopupContainer: () => document.body,
    },
  },
  {
    field: 'relateCode',
    label: '回写表单',
    component: 'Select',
    colProps: {
      span: 24,
    },
    componentProps: {
      optionFilterProp: 'label',
      showSearch: true,
      options: [],
      getPopupContainer: () => document.body,
    },
  },
  // {
  //   field: 'actionNode',
  //   label: '选择节点',
  //   colProps: {
  //     span: 24,
  //   },
  //   component: 'Select',
  //   componentProps: {
  //     showSearch: true,
  //     // fieldNames: { label: 'name', value: 'code', key: 'code' },

  //     optionFilterProp: 'label',
  //     getPopupContainer: () => document.body,
  //     options: [],
  //   },
  //   ifShow: ({ values }) => values.timestamp == 'nodeFinish',
  // },
  {
    field: 'divider-basic2',
    component: 'Input',
    label: '',
    colProps: {
      span: 24,
    },
    slot: 'divider-basic2',
  },
  // {
  //   field: 'formfield0',
  //   label: '设置字段值为',
  //   colProps: {
  //     span: 24,
  //   },
  //   component: 'Input',
  // },
  {
    field: 'fieldName',
    label: '',
    colProps: {
      span: 24,
    },
    component: 'Input',
    slot: 'fieldName',
    ifShow: ({ values }) => values.writeBackType == 0 || values.writeBackType == 2,
  },
  {
    field: 'divider-basic3',
    component: 'Divider',
    label: '插入模块设置12',
    colProps: {
      span: 24,
    },
    ifShow: ({ values }) => values.writeBackType == 1 || values.writeBackType == 2,
  },
  {
    label: '主键字段',
    field: 'primaryKey',
    component: 'Select',
    helpMessage: '仅插入主键字段记录不重复的数据',
    colProps: {
      span: 24,
    },
    componentProps: {
      showSearch: true,
      optionFilterProp: 'label',
      options: [],
      getPopupContainer: () => document.body,
    },
    ifShow: ({ values }) => values.writeBackType == 1 || values.writeBackType == 2,
  },
  {
    field: 'formfield2',
    label: '',
    colProps: {
      span: 24,
    },
    component: 'Input',
    slot: 'formfield2',
    ifShow: ({ values }) => values.writeBackType == 1 || values.writeBackType == 2,
  },
];

//处理数据get
export const getFormParams = ({ writeProp, scene }) => {
  console.log({ writeProp });
  let data: any = {};
  if (writeProp) {
    let xml;
    try {
      xml = $.parseXML(writeProp);

      const $xml = $(xml);
      $xml.find('node').each(function (i) {
        console.log('$(this)333-》', $(this));
        if ($(this).find('scene').text() == scene) {
          data = getWriteProp($(this));
          // data.timestamp = 'flowFinish';
          data.id = $(this).attr('id');
          return false;
        }
      });
    } catch (e) {
      console.error('getFormParams', e);
    }
  }
  return data;
};

const getWriteProp = (txml) => {
  const data: any = {};
  data.scene = txml.find('scene').text() || '';
  data.relateCode = txml.find('writeBackForm').text() || '';
  data.writeBackType = txml.find('writeBackType').text() || '';
  data.primaryKey = txml.find('primaryKey').text() || '';
  data.timestamp = txml.find('writeBackTime').text() || '';

  data.writeBackFieldList = [];
  txml.find('writeBackField').each(function () {
    console.log('prop', $(this));
    data.writeBackFieldList.push({
      fieldName: $(this).attr('fieldName'),
      writeBackMath: $(this).find('writeBackMath').text(),
      readonly: true,
    });
  });

  data.dbSource = txml.find('dbSource').text() || '';
  const insertFields = txml.find('insertFields').text() || '';
  if (insertFields) {
    data.insertFields = JSON.parse(insertFields);
  } else {
    data.insertFields = '';
  }

  data.conditionList = [];
  txml
    .find('condition')
    .children()
    .each(function () {
      data.conditionList.push({
        beginBracket: $(this).attr('beginBracket'),
        endBracket: $(this).attr('endBracket'),
        backField: $(this).attr('fieldName'),
        compare: $(this).find('compare').text(),
        backFieldValue: $(this).find('compareVal').text(),
        opType: $(this).find('compareVal').attr('type'),
        logical: $(this).find('logical').text(),
      });
    });

  return data;
};

//处理数据set
export const setFormParams = ({ writeProp, dataRef, type }) => {
  // writeProp = writeProp.replaceAll('><<', '>&lt;<');
  // writeProp = writeProp.replaceAll('><=<', '>&lt;=<');
  // writeProp = writeProp.replaceAll('>>', '>&gt;');

  const { writeBackType, timestamp } = dataRef;
  const uuid = dataRef.id ? dataRef.id : buildUUID(9);
  // <?xml version="1.0" encoding="UTF-8"?>
  let props = '';

  props += "<node id='" + uuid + "'>";

  props += `<scene>${dataRef.scene ? dataRef.scene : ''}</scene>`;
  props += `<dbSource>${dataRef.dbSource ? dataRef.dbSource : ''}</dbSource>`;
  props += `<writeBackForm>${dataRef.relateCode ? dataRef.relateCode : ''}</writeBackForm>`;
  props += `<writeBackType>${dataRef.writeBackType ? dataRef.writeBackType : ''}</writeBackType>`;
  props += `<primaryKey>${dataRef.primaryKey ? dataRef.primaryKey : ''}</primaryKey>`;
  props += `<writeBackTime>${dataRef.timestamp ? dataRef.timestamp : ''}</writeBackTime>`;
  //更新 更新并插入数据
  if (
    (writeBackType == 0 || writeBackType == 2 || type == 2) &&
    isArray(dataRef.writeBackFieldList) &&
    dataRef.writeBackFieldList.length
  ) {
    dataRef.writeBackFieldList.forEach((item) => {
      props += `<writeBackField fieldName='${item.fieldName}'>
                <writeBackMath> ${item.writeBackMath}</writeBackMath>
                </writeBackField>`;
    });
  }
  if (isArray(dataRef.conditionList) && dataRef.conditionList.length) {
    props += `<condition>`;
    dataRef.conditionList.forEach((item) => {
      item.compare = item.compare.replace('<', '&lt;');
      item.compare = item.compare.replace('>', '&gt;');

      props += `<conditionField beginBracket='${item.beginBracket}' endBracket='${item.endBracket}' fieldName='${item.backField}'>`;
      props += `<compare>${item.compare}</compare>`;
      props += `<compareVal type='${item.opType}'>${item.backFieldValue}</compareVal>`;
      props += `<logical>${item.logical}</logical>`;
      props += `</conditionField>`;
    });
    props += `</condition>`;
  }
  //插入 更新并插入数据
  if (
    (writeBackType == 1 || writeBackType == 2) &&
    isArray(dataRef.insertTableFieldsList) &&
    dataRef.insertTableFieldsList.length
  ) {
    props += `<insertFields>`;
    const obj = {};
    dataRef.insertTableFieldsList.forEach((item) => {
      obj[item.name] = item.math;
    });
    props += `${JSON.stringify(obj)}</insertFields>`;
  }
  props += '</node>';
  console.log('props', props);
  if (writeProp) {
    const xml = $.parseXML(writeProp);

    const $xml = $(xml);
    console.log("$xml.find('root').get(0)", $xml.find('root').get(0));
    $xml
      .find('root')
      .children()
      .each(function () {
        if ($(this).attr('id') == dataRef.id) {
          // 删除原节点
          $(this).remove();
          return false;
        }
      });
    // 新增节点
    const $elem = $($.parseXML(props));
    let newNode: any = null;
    if (typeof document.importNode == 'function') {
      newNode = document.importNode($elem.find('node').get(0), true);
    } else {
      newNode = $elem.find('node').get(0);
    }
    console.log('newNode', newNode);
    $xml.find('root').get(0).appendChild(newNode);
    console.log("$xml.find('root').get(0)", $xml.find('root').get(0));
    return $xml.xml();
  } else {
    const begin = '<?xml version="1.0" encoding="UTF-8"?><root>';
    const end = '</root>';
    props = begin + props + end;
    return props;
  }
};
